//
//  PhotoBrowserViewController.swift
//  weibo
//
//  Created by sanya on 15/7/3.
//  Copyright © 2015年 sanya. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

class PhotoBrowserViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    /// 加载视图
    override func loadView() {

        view = UIView(frame: UIScreen.mainScreen().bounds)
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        view.backgroundColor = UIColor.randomColor()
        
        collectionView.ff_Fill(view)
        saveButton.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: -12, y: -12))
        closeButton.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        collectionView.dataSource = self
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: SYPhotoBrowserCellReuseIdentifier)
    }
    func save(){
        print("save")
        // 1. 拿到当前的cell
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! PhotoBrowserCell
        // 2. 拿到图像
        let image = cell.imageIVew.image!
        // 3. 保存图像
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    func close(){
        print("close")
        dismissViewControllerAnimated(true, completion: nil)
    }
//  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image :UIImage, didFinishSavingWithError error:NSError?, contextInfo :AnyObject) {
        
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存出错")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }

    /// 构造方法
    init(urls:[NSURL],index:Int){
        print(urls)
        // 先初始化本类的属性
        imageURLs = urls
        currentIndex = index
        // 再调用父类的方法
        super.init(nibName: nil, bundle: nil)
        
    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        prepareLayout()
        // 跳转到指定的页面
        let indexpath = NSIndexPath(forRow: currentIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexpath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    /// 准备布局
    private func prepareLayout() {
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView.pagingEnabled = true
    }
    // 图像url 的数组
    private var imageURLs: [NSURL]
    // 图像索引的数组
    private var currentIndex:Int
    // MARK: － 控件懒加载
    
    lazy private var layout = UICollectionViewFlowLayout()
    
    lazy private var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    
    lazy private var saveButton:UIButton = UIButton(title: "保存", fontSize: 14)
    lazy private var closeButton:UIButton = UIButton(title: "关闭", fontSize: 14)
}

private let SYPhotoBrowserCellReuseIdentifier = "HMPhotoBrowserCellReuseIdentifier"

extension PhotoBrowserViewController:UICollectionViewDataSource,photoBrowserCellDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs.count
        
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(SYPhotoBrowserCellReuseIdentifier, forIndexPath: indexPath) as! PhotoBrowserCell
        cell.imageURL = imageURLs[indexPath.row]
        cell.photoDelegaet = self

        return cell
    }
    func PhotoBrowserCellDidTapImage() {
        // 关闭界面
        close()
    }

}


